from sqlalchemy import Column, String, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockDownLimit(Base):
    __tablename__ = 'stock_down_limit'
    id = Column(Integer, primary_key=True, autoincrement=True)
    qdate = Column(String(10), comment='日期（yyyy-MM-dd）')
    dm = Column(String(10), comment='代码')
    mc = Column(String(6), comment='名称')
    p = Column(String(20), comment='价格（元）')
    zf = Column(String(10), comment='跌幅（%）')
    cje = Column(String(20), comment='成交额（元）')
    lt = Column(String(20), comment='流通市值（元）')
    zsz = Column(String(20), comment='总市值（元）')
    pe = Column(String(20), comment='动态市盈率')
    hs = Column(String(10), comment='换手率（%）')
    lbc = Column(Integer, comment='连续跌停次数')
    lbt = Column(String(20), comment='最后封板时间（HH:mm:ss）')
    zj = Column(String(20), comment='封单资金（元）')
    fba = Column(String(20), comment='板上成交额（元）')
    zbc = Column(Integer, comment='开板次数')

    def __init__(self, qdate, dm, mc, p, zf, cje, lt, zsz, pe, hs, lbc, lbt, zj, fba, zbc):
        self.qdate = qdate
        self.dm = dm
        self.mc = mc
        self.p = p
        self.zf = zf
        self.cje = cje
        self.lt = lt
        self.zsz = zsz
        self.pe = pe
        self.hs = hs
        self.lbc = lbc
        self.lbt = lbt
        self.zj = zj
        self.fba = fba
        self.zbc = zbc

    @staticmethod
    def not_exist_insert(qdate, data_list):
        session = sessionmaker(bind=engine)()
        existing_stock_up_limit = session.query(StockDownLimit).filter_by(qdate=qdate).first()
        if existing_stock_up_limit:
            return
        for data in data_list:
            session.add(
                StockDownLimit(qdate=qdate, dm=data['dm'], mc=data['mc'], p=data['p'], zf=data['zf'], cje=data['cje'],
                             lt=data['lt'], zsz=data['zsz'], pe=data['pe'], hs=data['hs'], lbc=data['lbc'],
                             lbt=data['lbt'],
                             zj=data['zj'], fba=data['fba'], zbc=data['zbc']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
